rm(list = ls())
source("./functions/fun.R")

# Purpose: 
#  Build all indices for the JAGS model in the dataset. 
#  
#	
# 	
#	
#
#
# 
#





# LOAD the data. 
######

load("cmpempwide_all_east2.Rdata")



# BUILD indices and bridges.
######



# Generate 't', an ID for the t^th election a party is running and 
# 'T', a variable for the number of elections a party ran. 
# Simultaneously, construct the cross-election bridges. 
cmpempwide <- ddply(cmpempwide, c("countryname", "party", "study"), electionbridge1)



# 'entity' == countryname or 'EP' if the obs. belongs to EP election.
cmpempwide$entity <- cmpempwide$countryname
cmpempwide$entity[cmpempwide$study==2] <- "EP"


# Make IDs.
cmpempwide <- indexmaker(cmpempwide, c("entity"), "c")
cmpempwide <- indexmaker(cmpempwide, c("c", "year"), "ce")
cmpempwide <- indexmaker(cmpempwide, c("party", "study"), "i")



######################################################################
#############HERE THERE USED TO BE COUNTRY BRIDGES, GOT RID OF THEM###
######################################################################



# Re-indexing and make new ID.
cmpempwide <- reindexing(cmpempwide, "i")
cmpempwide <- indexmaker(cmpempwide, c("i", "t"), "it")

# Generate new index 'z' later used to choose the correct b_0 in the polynomials. 
cmpempwide$z <- 0
cmpempwide[cmpempwide$entity=="EP" & cmpempwide$skp!=1, ] <-
	ddply(cmpempwide[cmpempwide$entity=="EP" & cmpempwide$skp!=1, ], "party", b0indicator)





# Construct index to select phi prior. 
load("chesprior_east.Rdata")
ches <- chesprior$ches
nfam <- chesprior$nfam

matcher <- cbind(obsid=seq(1,nrow(cmpempwide)), cmpid=cmpempwide$party, ches[match(cmpempwide$party, ches$cmp),])
matcher$partyfam[is.na(matcher$partyfam)] <- (nfam+1)
cmpempwide$w <- matcher$partyfam




# Generate 'parameter selection' datasets. 
selects <- paramselect(cmpempwide)



# SAVE #
########

for_jags <- list(cmpemp=cmpempwide, 
						mu0=chesprior$mu0, 
						sigmainv0=chesprior$sigmainv0, 
						phi.select=selects$phi.select, 
						theta.select=selects$theta.select, 
						rho.select=selects$rho.select )
						
save(for_jags, file="./models/m300/for_jags.Rdata")


